// 导入API工具函数
import {get} from './api.js';

// API基础路径
const API_ENDPOINT = '/users/search';

// 分页状态
let currentPage = 1;
let pageSize = 5;
let totalPages = 1;
let totalItems = 0;
let lastQueryParams = {};

// 查询函数
async function queryStudent(page = 1) { 
    const studentId = document.getElementById('studentId').value.trim();
    const name = document.getElementById('name').value.trim();
    const major = document.getElementById('major').value;
    const resultBody = document.getElementById('resultBody');

    // 清空结果区域
    resultBody.innerHTML = '<tr><td colspan="6" style="text-align:center;">加载中...</td></tr>';

    try{
        // 构建查询参数
        const params = new URLSearchParams();
        if (studentId) params.append('sid', studentId);
        if (name) params.append('name', name);
        if (major) params.append('major', major);
        // 添加分页参数
        params.append('page', page);
        params.append('pageSize', pageSize);

        // 发送GET请求
        const response = await get(`${API_ENDPOINT}?${params}`);

        // 检查响应是否成功
        if (response.success && response.data) {
            // 更新分页信息
            currentPage = response.pagination.page;
            pageSize = response.pagination.pageSize;
            totalPages = response.pagination.totalPages;
            totalItems = response.pagination.total;
            
            renderResults(response.data);
            updatePaginationControls();
        } else {
            showNoResults('未找到匹配的学生');
            resetPagination();
        }
    } catch (error) {
        console.error('查询失败:', error);
        showNoResults(`查询失败: ${error.message}`);
        resetPagination();
    }
}

// 渲染查询结果
function renderResults(students) { 
    const resultBody = document.getElementById('resultBody');
    resultBody.innerHTML = ''; // 清空结果区域

    students.forEach(student => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${student.sid}</td>
            <td>${student.name}</td>
            <td>${student.gender}</td>
            <td>${student.birth}</td>
            <td>${student.major}</td>
            <td>${student.credits}</td>
        `;
        row.onclick = () => showExtraInfo(student);
        resultBody.appendChild(row);
    })
}

// 显示没有结果
function showNoResults(message) { 
    const resultBody = document.getElementById('resultBody');
    resultBody.innerHTML = `<tr><td colspan="6" style="text-align:center;">${message}</td></tr>`;
}

// 显示附加信息
function showExtraInfo(student) {
    document.getElementById('note').textContent = student.remark || '暂无备注';

    const photoElement = document.getElementById('photo');
    
    // 处理图片 - 直接使用 Base64 数据
    if (student.photo && typeof student.photo === 'string' && student.photo.trim() !== '') {
        let photoData = student.photo.trim();
        
        // 确保是完整的 data URL
        if (!photoData.startsWith('data:image')) {
            // 如果缺少前缀，自动添加（假设为 PNG 格式）
            photoData = `data:image/png;base64,${photoData}`;
        }
        
        photoElement.src = photoData;
    } else {
        photoElement.src = '../images/默认头像.png';
    }
}

// 跟新分页控件状态
function updatePaginationControls() {
    const pageInfo = document.getElementById('pageInfo');
    pageInfo.textContent = `第 ${currentPage} 页，共 ${totalPages} 页（共 ${totalItems} 条）`;
    
    const prevButton = document.getElementById('prevPage');
    const nextButton = document.getElementById('nextPage');
    
    prevButton.disabled = currentPage <= 1;
    nextButton.disabled = currentPage >= totalPages;
}

// 重置分页信息
function resetPagination() {
    currentPage = 1;
    totalPages = 1;
    totalItems = 0;
    updatePaginationControls();
}

// 翻到上一页
function goToPrevPage() {
    if (currentPage > 1) {
        queryStudent(currentPage - 1);
    }
}

// 翻到下一页
function goToNextPage() {
    if (currentPage < totalPages) {
        queryStudent(currentPage + 1);
    }
}

// 页大小改变
function handlePageSizeChange() {
    const select = document.getElementById('pageSizeSelect');
    pageSize = parseInt(select.value);
    queryStudent(1); // 重置到第一页
}

// 绑定事件
function bindEvents() {
    const queryButton = document.getElementById('queryButton');
    const prevButton = document.getElementById('prevPage');
    const nextButton = document.getElementById('nextPage');
    const pageSizeSelect = document.getElementById('pageSizeSelect');


    if (queryButton) {
        queryButton.addEventListener('click', queryStudent);
    }
    if (prevButton) prevButton.addEventListener('click', goToPrevPage);
    if (nextButton) nextButton.addEventListener('click', goToNextPage);

    // 页大小改变事件
    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', handlePageSizeChange);
    }

    // 回车键查询
    const studentIdInput = document.getElementById('studentId');
    if (studentIdInput) {
        studentIdInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                queryStudent(1);
            }
        });
    }
}


// 页面加载完成后自动查询所有学生
document.addEventListener('DOMContentLoaded', () => {
    bindEvents();
    queryStudent(1);
});

export { queryStudent };